package admin

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/garray"
	"duoke/utils/gconv"
	"duoke/utils/gtime"
	"duoke/utils/orm"
	"duoke/utils/request"
	"duoke/utils/response"
	"fmt"
	"github.com/gin-gonic/gin"
)

var Group = new(groupCtl)

type groupCtl struct{}

func (ctl *groupCtl) List(c *gin.Context) {
	accountR, _ := service.Request.Account(c)
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	where := "pay_state = 1 "
	if req.Keyword != "" {
		where += "AND (user_id ='" + req.Keyword + "' OR order_no ='" + req.Keyword + "' OR nickname ='" + req.Keyword + "' OR name ='" + req.Keyword + "' OR phone ='" + req.Keyword + "' )"
	}
	if req.Keyword2 != "" {
		where2 := "is_head =0 AND pay_state = 1 AND (user_id ='" + req.Keyword2 + "' OR order_no ='" + req.Keyword2 + "' OR nickname ='" + req.Keyword2 + "' OR name ='" + req.Keyword2 + "' OR phone ='" + req.Keyword2 + "' )"
		order2 := new(tables.Order)
		has, _ := orm.Db.Desc("id").Where("acid =?", accountR.Id).Where(where2).Get(order2)
		if has {
			where += "AND id = " + gconv.String(order2.GroupId) + " "
		} else {
			where += "AND id = -1 "
		}
	}
	if req.State != "" {
		where += "AND hx_state = '" + req.State + "' "
	}
	if req.GroupState != "" {
		where += "AND group_state = '" + req.GroupState + "' "
	}
	if req.IsRobot != "" {
		where += "AND is_robot = '" + req.IsRobot + "' "
	}
	if req.GoodsId != "" {
		where += "AND goods_id = '" + req.GoodsId + "' "
	}
	if req.TimeRange != nil && len(req.TimeRange) == 2 {
		startTime := gtime.StrToTime(req.TimeRange[0])
		endTime := gtime.StrToTime(req.TimeRange[1])
		where += "AND pay_time >= '" + gconv.String(startTime) + "' "
		where += "AND pay_time <= '" + gconv.String(endTime) + "' "
		fmt.Println(where)
	}
	if req.GroupNum != "" {
		where += "AND group_num = '" + req.GroupNum + "' "
	}
	if req.GroupMemberNum != "" {
		where += "AND group_member_num = '" + req.GroupMemberNum + "' "
	}
	if req.IsNewOld != "" {
		where += "AND is_new_old = '" + req.IsNewOld + "' "
	}
	list, err := service.Group.List(c, where, 10000, "")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", list)
}
func (ctl *groupCtl) Page(c *gin.Context) {
	accountR, _ := service.Request.Account(c)
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	where := "pay_state = 1 AND is_head = 1 "
	if req.Keyword != "" {
		where += "AND (order_no like'%" + req.Keyword + "%' OR nickname like'%" + req.Keyword + "%' OR name like'%" + req.Keyword + "%' OR phone like'%" + req.Keyword + "%' )"
	}
	if req.Keyword2 != "" {
		where2 := "is_head =0 AND pay_state = 1 AND (order_no like'%" + req.Keyword2 + "%' OR nickname like'%" + req.Keyword2 + "%' OR name like'%" + req.Keyword2 + "%' OR phone like'%" + req.Keyword2 + "%' ) "
		if req.IsRobot != "" {
			where2 += "AND is_robot = '" + req.IsRobot + "' "
		}
		order2 := new(tables.Order)
		has, _ := orm.Db.Desc("id").Where("acid =?", accountR.Id).Where(where2).Get(order2)
		if has {
			where += "AND group_id = " + gconv.String(order2.GroupId) + " "
		} else {
			where += "AND group_id = -1 "
		}
	}
	if req.State != "" {
		where += "AND hx_state = '" + req.State + "' "
	}
	if req.IsRobot != "" {
		where += "AND is_robot = '" + req.IsRobot + "' "
	}
	if req.GroupState != "" {
		where += "AND group_state = '" + req.GroupState + "' "
	}
	if req.IsRobot != "" {
		where += "AND is_robot = '" + req.IsRobot + "' "
	}
	if req.GoodsId != "" {
		where += "AND goods_id = '" + req.GoodsId + "' "
	}
	if req.TimeRange != nil && len(req.TimeRange) == 2 {
		startTime := gtime.StrToTime(req.TimeRange[0])
		endTime := gtime.StrToTime(req.TimeRange[1])
		where += "AND pay_time >= '" + gconv.String(startTime) + "' "
		where += "AND pay_time <= '" + gconv.String(endTime) + "' "
		fmt.Println(where)
	}
	if req.GroupNum != "" {
		where += "AND group_num = '" + req.GroupNum + "' "
	}
	if req.GroupMemberNum != "" {
		where += "AND group_member_num = '" + req.GroupMemberNum + "' "
	}
	if req.IsNewOld != "" {
		where += "AND is_new_old = '" + req.IsNewOld + "' "
	}
	list, total, err := service.Group.Page(c, req, where, "")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", gin.H{"total": total, "list": list})
}

// 团长单，升团数
func (ctl *groupCtl) Rise(c *gin.Context) {
	req := request.JsonMap(c)
	orderId := gconv.Int(req["orderId"])
	if orderId == 0 {
		response.Error(c, "团长单ID不存在", nil)
		return
	}
	headOrder := new(tables.Order)
	has, err := orm.Db.Where("id =? AND is_head =1 AND pay_state = 1", orderId).Get(headOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "团长单不存在", nil)
		return
	}
	order := new(tables.Order)
	order.GroupNum = headOrder.GroupNum + 1
	order.GroupState = 0
	affected, err := orm.Db.Where("group_id =?  AND pay_state = 1", headOrder.Id).Cols("group_num", "group_state").Update(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if affected == 0 {
		response.Error(c, "操作失败", nil)
		return
	}
	response.Success(c, "操作成功", nil)
}

// 团长单，降团数
func (ctl *groupCtl) Drop(c *gin.Context) {
	req := request.JsonMap(c)
	orderId := gconv.Int(req["orderId"])
	if orderId == 0 {
		response.Error(c, "团长单ID不存在", nil)
		return
	}
	headOrder := new(tables.Order)
	has, err := orm.Db.Where("id =? AND is_head =1 AND pay_state = 1", orderId).Get(headOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "团长单不存在", nil)
		return
	}
	if headOrder.GroupState == 1 {
		response.Error(c, "该团已满团，无法降团数", nil)
		return
	}
	if headOrder.GroupNum <= headOrder.GroupMemberNum {
		response.Error(c, "该团已满团，无法降团数", nil)
		return
	}
	order := new(tables.Order)
	order.GroupNum = headOrder.GroupNum - 1
	if headOrder.GroupNum-headOrder.GroupMemberNum == 1 {
		order.GroupState = 1
	}
	affected, err := orm.Db.Where("group_id =?  AND pay_state = 1", headOrder.Id).Cols("group_num", "group_state").Update(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if affected == 0 {
		response.Error(c, "操作失败", nil)
		return
	}
	response.Success(c, "操作成功", nil)
}

// 设置团长
func (ctl *groupCtl) SetHead(c *gin.Context) {
	req := request.JsonMap(c)
	orderId := gconv.Int(req["orderId"])
	if orderId == 0 {
		response.Error(c, "订单ID不存在", nil)
		return
	}
	order := new(tables.Order)
	has, err := orm.Db.Where("id =? AND is_head =0 AND pay_state = 1", orderId).Get(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "订单不存在", nil)
		return
	}
	headOrder := new(tables.Order)
	has, err = orm.Db.Where("id =? AND is_head =1 AND pay_state = 1", order.GroupId).Get(headOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "团长订单不存在", nil)
		return
	}
	order.GroupId = orderId
	order.GroupNum = order.GroupNum
	order.GroupMemberNum = 1
	order.GroupState = 0
	order.HeadUserId = order.UserId
	order.IsHead = 1
	affected, err := orm.Db.ID(orderId).Cols("group_id", "group_num", "group_member_num", "group_state", "head_user_id", "is_head").Update(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if affected == 0 {
		response.Error(c, "操作失败", nil)
		return
	}
	// 设置团长单状态
	headOrder.GroupMemberNum = headOrder.GroupMemberNum - 1
	headOrder.GroupState = 0
	affected, err = orm.Db.ID(headOrder.Id).Cols("group_member_num", "group_state").Update(headOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if affected == 0 {
		response.Error(c, "操作失败", nil)
		return
	}
	response.Success(c, "操作成功", nil)
}

// 调团
func (ctl *groupCtl) Change(c *gin.Context) {
	req := request.JsonMap(c)
	orderId := gconv.Int(req["orderId"])
	if orderId == 0 {
		response.Error(c, "订单ID不存在", nil)
		return
	}
	changeOrderId := gconv.Int(req["changeOrderId"])
	if orderId == 0 {
		response.Error(c, "目标团ID不存在", nil)
		return
	}
	if orderId == changeOrderId {
		response.Error(c, "目标团不能是自己", nil)
		return
	}
	// 要操作订单
	order := new(tables.Order)
	has, err := orm.Db.Where("id =? AND pay_state = 1", orderId).Get(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "目标订单不存在", nil)
		return
	}
	// 原来团
	oldGroupId := order.GroupId
	oldGroupMemberNum := order.GroupMemberNum
	// 团长订单
	changeOrder := new(tables.Order)
	has, err = orm.Db.Where("id =? AND is_head =1 AND pay_state = 1", changeOrderId).Get(changeOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "目标团不存在或不是团长", nil)
		return
	}
	// 原订单
	if order.IsHead == 1 && order.GroupMemberNum > 1 {
		response.Error(c, "原团已存在团员不可以调团", nil)
		return
	}
	if order.GroupId == changeOrder.GroupId {
		response.Error(c, "同一个团无需改动", nil)
		return
	}
	order.IsHead = 0
	order.HeadUserId = changeOrder.UserId
	order.GroupId = changeOrder.GroupId
	order.GroupNum = changeOrder.GroupNum
	order.GroupMemberNum = changeOrder.GroupMemberNum
	order.GroupState = changeOrder.GroupState
	_, err = orm.Db.ID(order.Id).Cols("group_id", "group_num", "group_member_num", "group_state", "head_user_id", "is_head").Update(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 目标团
	if changeOrder.GroupNum-changeOrder.GroupMemberNum == 0 {
		changeOrder.GroupNum = changeOrder.GroupNum + 1
		changeOrder.GroupState = 1
	}
	if changeOrder.GroupNum-changeOrder.GroupMemberNum == 1 {
		changeOrder.GroupState = 1
	}
	changeOrder.GroupMemberNum = changeOrder.GroupMemberNum + 1
	_, err = orm.Db.Where("group_id =? AND pay_state = 1", order.GroupId).Cols("group_member_num", "group_state").Update(changeOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 最初团，团成员减1，团状态不满团
	oldNewOrder := new(tables.Order)
	oldNewOrder.GroupMemberNum = oldGroupMemberNum - 1
	oldNewOrder.GroupState = 0
	_, err = orm.Db.Where("group_id =? AND pay_state = 1", oldGroupId).Cols("group_member_num", "group_state").Update(oldNewOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "操作成功", nil)
}

// 增加机器人
func (ctl *groupCtl) AddRobot(c *gin.Context) {
	accountR, _ := service.Request.Account(c)
	req := request.JsonMap(c)
	orderId := gconv.Int(req["orderId"])
	if orderId == 0 {
		response.Error(c, "团长单ID不存在", nil)
		return
	}
	headOrder := new(tables.Order)
	has, err := orm.Db.Where("id =? AND is_head =1 AND pay_state = 1", orderId).Get(headOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !has {
		response.Error(c, "团长单不存在", nil)
		return
	}
	type1 := gconv.Int(req["type"])
	nickname := gconv.String(req["nickname"])
	avatar := gconv.String(req["avatar"])
	robotId := 0
	if type1 == 1 {
		orders := make([]tables.Order, 0)
		err := orm.Db.Where("acid =? AND pay_state = 1 AND is_robot = 1 AND refund_state = 0 AND goods_id =?", accountR.Id, headOrder.GoodsId).Find(&orders)
		if err != nil {
			response.Error(c, err.Error(), nil)
			return
		}
		// fmt.Println(orders)
		hasIds := make([]int, 0)
		hasIdsStr := "0"
		for _, v := range orders {
			if !garray.InInt(v.RobotId, hasIds) {
				hasIds = append(hasIds, v.RobotId)
			}
		}
		if len(hasIds) > 0 {
			hasIdsStr = garray.IntToString(",", hasIds)
		}
		robot := new(tables.Robot)
		has, err := orm.Db.Where("acid =? AND id not in ("+hasIdsStr+")", accountR.Id).Get(robot)
		if err != nil {
			response.Error(c, err.Error(), nil)
			return
		}
		if !has {
			response.Error(c, "没有符合条件的机器人，请到用户里面添加机器人", nil)
			return
		}
		nickname = robot.Nickname
		avatar = robot.Avatar
		robotId = robot.Id
	}
	if nickname == "" {
		response.Error(c, "昵称必须填写", nil)
		return
	}
	if avatar == "" {
		avatar = "https://himg.bdimg.com/sys/portrait/hotitem/wildkid/47"
	}
	headGroupNum := headOrder.GroupNum
	headGroupMemberNum := headOrder.GroupMemberNum
	// 创建订单
	headOrder.Nickname = nickname
	headOrder.Avatar = avatar
	headOrder.OrderNo = "00000000"
	headOrder.Name = "00000000"
	headOrder.Phone = "00000000"
	headOrder.FromId = 0
	headOrder.FromId2 = 0
	headOrder.StaffId = 0
	headOrder.IsRobot = 1
	headOrder.IsHead = 0
	headOrder.UserId = 0
	headOrder.RefundState = 0
	headOrder.PayAmount = "0"
	headOrder.RobotId = robotId
	headOrder.CreatedAt = gconv.Int(gtime.TimeStamp())
	headOrder.UpdatedAt = gconv.Int(gtime.TimeStamp())
	affected, err := orm.Db.Omit("id").Insert(headOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if affected == 0 {
		response.Error(c, "操作失败1", nil)
		return
	}
	order := new(tables.Order)
	order.GroupNum = headOrder.GroupNum
	if headGroupNum-headGroupMemberNum == 1 {
		order.GroupState = 1
	}
	if headGroupNum-headGroupMemberNum == 0 {
		order.GroupNum = headOrder.GroupNum + 1
		order.GroupState = 1
	}
	order.GroupMemberNum = headOrder.GroupMemberNum + 1
	affected, err = orm.Db.Where("group_id =?  AND pay_state = 1", headOrder.GroupId).Cols("group_num", "group_state", "group_member_num").Update(order)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "操作成功", nil)
}
func (ctl *groupCtl) RankingVersion(c *gin.Context) {
	var req model.ReqListV2
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list, total, err := service.Group.RankingVersion(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{"total": total, "list": list})
}
